<template>
	<view class="moment-detail-page">
		<custom-navbar class="my-navigation" title="动态详情" :isReturnVisible="true" :isAddVisible="false" />
		<!-- 展示动态基本信息 -->
		<view class="moment-message">
			<!-- 第一行 -->
			<view class="title-row">
				<image class="author-avatar" :src="momentDetail.authorAvatar"></image>
				<view class="author-info">
					<view class="author-nickname">{{momentDetail.authorName}}</view>
					<view class="post-time">
						<text style="color: darkgrey; font-size: 12px;">发表于：</text>
						<text class="created-time">{{ momentDetail.createdTime }}</text>
					</view>
				</view>
				<view class="delete-btn" v-if="momentDetail.isAuthor" @click="handleDeleteMoment()">
					<image src="/static/icons/delete.png" class="delete-btn-icon"></image>
				</view>
			</view>
			<!-- 文字内容 -->
			<view class="content" v-if="momentDetail.content!=null">
				{{ momentDetail.content }}
			</view>
			<!-- 自定义图片预览组件 -->
			<custom-image-preview :visible="previewVisible" :urls="previewUrls" :current-index="previewIndex"
				@close="previewVisible=false" @index-change="previewIndex=$event">
			</custom-image-preview>
			<!-- 图片内容 -->
			<view class="image-grid">
				<view v-for="(imageItem,index) in momentDetail.picUrlList" :key="index" class="image-item-container"
					@click="openPreview(momentDetail.picUrlList, index)">
					<image class="image-item" :src="imageItem"></image>
				</view>
			</view>

			<!-- 操作行 -->
			<view class="opreation-row">
				<view class="like-btn" @click="handleLikeOrUnlike()">
					<image src="/static/icons/like_liked.png" v-if="momentDetail.isLiked" class="like-btn"></image>
					<image src="/static/icons/like_default.png" v-else class="like-btn"></image>
				</view>
				<view class="like-count" v-if="momentDetail.likeCount<100">{{ momentDetail.likeCount }}</view>
				<view class="like-count" v-else>99+</view>
				<view class="comment-btn" @click="handleComment">
					<image src="/static/icons/comment.png" class="comment-btn"></image>
				</view>

				<view class="comment-count" v-if="momentDetail.replyCount<100">{{ momentDetail.replyCount }}</view>
				<view class="comment-count" v-else>99+</view>
			</view>
		</view>

		<!-- 发表评论区域 -->
		<view class="comment-input-area">
			<textarea class="comment-input"
				:placeholder="(momentDetail && momentDetail.replyCount > 0) ? '写下你的评论...' : '快来抢沙发'"
				v-model="newCommentContent"></textarea>
			<!-- 图片上传区 -->
			<view class="comment-image-upload">
				<view class="comment-image-container">
					<view v-for="(img, index) in newCommentImages" :key="index" class="comment-image-preview">
						<image :src="img" mode="aspectFill"></image>
						<view class="comment-delete-btn" @click="removeCommentImage(index)">×</view>
					</view>
					<view class="comment-add-image-btn" @click="addCommentImage" v-if="newCommentImages.length < 9">
						<image src="/static/icons/add_image.png" mode="aspectFit"></image>
					</view>
				</view>
			</view>

			<!-- 发表按钮 -->
			<button class="submit-comment-btn" @click="submitComment" :disabled="submittingComment">
				{{ submittingComment ? '发表中...' : '发表评论' }}
			</button>
		</view>

		<!-- 评论统计 -->
		<view class="comment-count-header">
			共 {{ momentDetail.replyCount }} 条评论和回复
		</view>

		<!-- 评论列表 -->
		<view class="comment-list">
			<view v-for="(comment, index) in momentDetail.commentReplyVOList" :key="comment.id" class="comment-item">
				<!-- 评论头部 -->
				<view class="comment-header">
					<image class="comment-avatar" :src="comment.fromUserAvatar"></image>
					<view class="comment-author">
						<text class="comment-nickname">{{ comment.fromUserName }}</text>
						<text v-if="comment.isAuthor" class="comment-author-tag">作者</text>
					</view>
					<view class="comment-time">{{ comment.createdTime }}</view>
				</view>

				<!-- 评论内容 -->
				<view class="comment-content">{{ comment.content }}</view>

				<!-- 评论图片 -->
				<view class="comment-images" v-if="comment.picUrlList && comment.picUrlList.length > 0">
					<view v-for="(img, imgIndex) in comment.picUrlList" :key="imgIndex" class="comment-image-item">
						<image :src="img" mode="aspectFill"></image>
					</view>
				</view>

				<!-- 评论操作 -->
				<view class="comment-actions">
					<view class="comment-like" @click="toggleCommentLike(comment)">
						<image
							:src="comment.isLiked ? '/static/icons/like_liked.png' : '/static/icons/like_default.png'"
							class="like-icon"></image>
						<text>{{ comment.likeCount }}</text>
					</view>
					<view class="comment-reply-btn" @click="openReplyInput(comment, comment)">
						回复
					</view>
					<!-- 删除按钮 -->
					<view class="comment-item-delete-btn" v-if="comment.isAuthor"
						@click="handleDeleteCommentReply(comment)">
						<image src="/static/icons/delete.png" class="delete-icon"></image>
					</view>
				</view>
				<!-- 回复区域 -->
				<view class="reply-section">
					<!-- 查看回复按钮 -->
					<view class="view-replies-btn" v-if="comment.replyCount>0&&!comment.showReplies"
						@click="showReplies(comment)">
						查看回复（{{ comment.replyCount }}）
					</view>
					<!-- 回复列表 -->
					<view class="reply-list" v-if="comment.showReplies">
						<!-- 部分回复 -->
						<view v-if="!comment.showAllReplies" v-for="(reply, replyIndex) in comment.partialReplies"
							:key="reply.id" class="reply-item">
							<!-- 回复头部 -->
							<view class="reply-header">
								<image class="reply-avatar" :src="reply.fromUserAvatar"></image>
								<view class="reply-author">
									<text class="reply-nickname">{{ reply.fromUserName }}</text>
									<text v-if="reply.isAuthor" class="reply-author-tag">作者</text>
									<text> 回复 </text>
									<text class="reply-to-nickname">{{ reply.toUserName }}</text>
								</view>
							</view>
							<!-- 回复内容 -->
							<view class="reply-content">{{ reply.content }}</view>
							<!-- 回复图片 -->
							<view class="reply-images" v-if="reply.picUrlList && reply.picUrlList.length > 0">
								<view v-for="(img, imgIndex) in reply.picUrlList" :key="imgIndex"
									class="reply-image-item">
									<image :src="img" mode="aspectFill"></image>
								</view>
							</view>
							<!-- 回复操作 -->
							<view class="reply-actions">
								<view class="reply-time">{{ reply.createdTime }}</view>
								<view class="reply-like" @click="toggleReplyLike(reply)">
									<image
										:src="reply.isLiked ? '/static/icons/like_liked.png' : '/static/icons/like_default.png'"
										class="like-icon"></image>
									<text>{{ reply.likeCount }}</text>
								</view>
								<view class="reply-reply-btn" @click="openReplyInput(comment, reply)">
									回复
								</view>
								<!-- 删除按钮 -->
								<view class="reply-item-delete-btn" v-if="reply.isAuthor"
									@click="handleDeleteCommentReply(reply)">
									<image src="/static/icons/delete.png" class="delete-icon"></image>
								</view>
							</view>
						</view>
						<!-- 加载全部回复按钮 -->
						<view v-if="comment.replyCount > comment.partialReplies.length && !comment.showAllReplies"
							class="
							load-all-replies-btn" @click="loadAllReplies(comment)">
							查看全部 {{ comment.replyCount }} 条回复
						</view>
						<!-- 全部回复 -->
						<view v-if="comment.showAllReplies" v-for="(reply, replyIndex) in comment.flattenedReplies"
							:key="reply.id" class="reply-item">
							<!-- 回复头部 -->
							<view class="reply-header">
								<image class="reply-avatar" :src="reply.fromUserAvatar"></image>
								<view class="reply-author">
									<text class="reply-nickname">{{ reply.fromUserName }}</text>
									<text v-if="reply.isAuthor" class="reply-author-tag">作者</text>
									<text> 回复 </text>
									<text class="reply-to-nickname">{{ reply.toUserName }}</text>
								</view>
							</view>
							<!-- 回复内容 -->
							<view class="reply-content">{{ reply.content }}</view>
							<!-- 回复图片 -->
							<view class="reply-images" v-if="reply.picUrlList && reply.picUrlList.length > 0">
								<view v-for="(img, imgIndex) in reply.picUrlList" :key="imgIndex"
									class="reply-image-item">
									<image :src="img" mode="aspectFill"></image>
								</view>
							</view>
							<!-- 回复操作 -->
							<view class="reply-actions">
								<view class="reply-time">{{ reply.createdTime }}</view>
								<view class="reply-like" @click="toggleReplyLike(reply)">
									<image
										:src="reply.isLiked ? '/static/icons/like_liked.png' : '/static/icons/like_default.png'"
										class="like-icon"></image>
									<text>{{ reply.likeCount }}</text>
								</view>
								<view class="reply-reply-btn" @click="openReplyInput(comment, reply)">
									回复
								</view>
								<!-- 删除按钮 -->
								<view class="reply-item-delete-btn" v-if="reply.isAuthor"
									@click="handleDeleteCommentReply(reply)">
									<image src="/static/icons/delete.png" class="delete-icon"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 回复输入框组件 -->
		<view class="reply-input-container" v-if="showReplyInput">
			<view class="reply-input-header">
				<text>回复 {{replyTargetName}}</text>
				<view class="close-btn" @click="closeReplyInput">×</view>
			</view>
			<textarea class="reply-textarea" placeholder="输入回复内容..." v-model="replyContent" auto-height></textarea>
			<!-- 图片上传区 -->
			<view class="reply-image-upload">
				<view class="reply-image-container">
					<view v-for="(img, index) in replyImages" :key="index" class="reply-image-preview">
						<image :src="img" mode="aspectFill"></image>
						<view class="reply-delete-btn" @click="removeReplyImage(index)">×</view>
					</view>
					<view class="reply-add-image-btn" @click="addReplyImage" v-if="replyImages.length < 9">
						<image src="/static/icons/add_image.png" mode="aspectFit"></image>
					</view>
				</view>
			</view>
			<!-- 操作按钮 -->
			<view class="reply-action-buttons">
				<view class="reply-upload-btn" @click="addReplyImage">
					<image src="/static/icons/image_upload.png" class="upload-icon"></image>
				</view>
				<button class="reply-send-btn" @click="sendReply" :disabled="sendingReply">
					{{ sendingReply ? '发送中...' : '发送' }}
				</button>
			</view>
		</view>
		<!-- 遮罩层 -->
		<view class="mask" v-if="showReplyInput" @click="closeReplyInput"></view>
	</view>
</template>

<script setup>
	import customNavbar from '../../components/custom-navbar.vue';
	import {
		ref,
		computed
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		deleteMoment,
		getMomentDetail,
		likeOrUnlikeMoment
	} from '../../api/moment';
	import CustomImagePreview from '../../components/custome-image-preview.vue';
	import {
		batchUploadFiles
	} from '../../api/file';
	import {
		addCommentReply,
		likeOrUnlikeCommentReply,
		deleteCommentReply
	} from '../../api/commentReply';

	const getCurrentMomentDetail = async () => {
		try {
			// 保存当前评论的展开状态
			const currentCommentStates = {};
			if (momentDetail.value && momentDetail.value.commentReplyVOList) {
				momentDetail.value.commentReplyVOList.forEach(comment => {
					// 只保存已展开评论的状态
					if (comment.showReplies || comment.showAllReplies) {
						currentCommentStates[comment.id] = {
							showReplies: comment.showReplies,
							showAllReplies: comment.showAllReplies
						};
					}
				});
			}
			const res = await getMomentDetail(momentId.value);
			console.log('API返回的完整响应:', res);
			if (res && res.data) {
				console.log('实际数据:', res.data);
				momentDetail.value = res.data;
				// 恢复评论的展开状态
				if (momentDetail.value.commentReplyVOList) {
					momentDetail.value.commentReplyVOList.forEach(comment => {
						const savedState = currentCommentStates[comment.id];
						if (savedState) {
							comment.showReplies = savedState.showReplies;
							comment.showAllReplies = savedState.showAllReplies;
						} else {
							// 新评论默认状态
							comment.showReplies = false;
							comment.showAllReplies = false;
						}
						// 确保所有回复都被处理
						processCommentReplies(comment);
					});
				}
			} else {
				console.warn('API响应中没有data字段:', res);
			}

		} catch (error) {
			console.error('获取动态详情失败:', error);
			uni.showToast({
				title: '获取详情失败',
				icon: 'none'
			});
		}
	}
	// 处理评论的回复数据
	function processCommentReplies(comment) {
		// 确保有children数组
		if (!comment.children) {
			comment.children = [];
		}

		// 添加展平的回复列表
		comment.flattenedReplies = getFlattenedReplies(comment);

		// 初始化部分回复（最多2条）
		comment.partialReplies = getPartialReplies(comment);

		// 确保所有子回复也被处理
		if (comment.children && comment.children.length > 0) {
			comment.children.forEach(child => {
				processCommentReplies(child);
			});
		}
	}

	function previewImage(urls, current) {
		uni.previewImage({
			current: current, // 当前图片索引
			urls: urls, // 所有图片URL列表
			indicator: 'number', // 显示数字指示器
			loop: true, // 支持循环预览
		});
	}

	// 添加预览状态
	const previewVisible = ref(false);
	const previewUrls = ref([]);
	const previewIndex = ref(0);

	function openPreview(urls, index) {
		previewUrls.value = urls;
		previewIndex.value = index;
		previewVisible.value = true;
	}


	const momentId = ref(null);
	const momentDetail = ref();
	// const momentDetail = ref({
	// 	id: 1,
	// 	content: "今天这个护工要把我给气死了！",
	// 	picUrlList: [
	// 		"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 		"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 		"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 		"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 		"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 		"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3"
	// 	],
	// 	replyCount: 3,
	// 	likeCount: 0,
	// 	createdBy: 4,
	// 	authorName: "zs",
	// 	authorAvatar: "https://ts1.tc.mm.bing.net/th/id/OIP-C.x1PyBhyeDOzT5_Wx5WiLJAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3",
	// 	createdTime: "2025-07-07 13:41:12",
	// 	isLiked: false,
	// 	commentReplyVOList: [{
	// 		rootNode: true,
	// 		leafNode: false,
	// 		children: [{
	// 			rootNode: false,
	// 			leafNode: false,
	// 			children: [{
	// 				rootNode: false,
	// 				leafNode: true,
	// 				children: null,
	// 				id: 3,
	// 				momentId: 1,
	// 				replyType: 2,
	// 				replierAuthor: 0,
	// 				toId: 2,
	// 				content: "啊，我那个护工还行，挺好！",
	// 				picUrlList: [],
	// 				createdTime: "2025-07-07 20:55:20",
	// 				replyCount: 0,
	// 				likeCount: 0,
	// 				isDeleted: 0,
	// 				fromUserId: 5,
	// 				toUserId: 4,
	// 				fromUserName: "zhangsi",
	// 				toUserName: "zs",
	// 				fromUserAvatar: "https://tse1-mm.cn.bing.net/th/id/OIP-C.-ha6wAB8QEtiNtN5KPygnQAAAA?w=174&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 				toUserAvatar: "https://ts1.tc.mm.bing.net/th/id/OIP-C.x1PyBhyeDOzT5_Wx5WiLJAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3",
	// 				parentId: 2,
	// 				isLiked: false,
	// 				isAuthor: false,
	// 				nodeId: 3,
	// 				nodePId: 2
	// 			}],
	// 			id: 2,
	// 			momentId: 1,
	// 			replyType: 2,
	// 			replierAuthor: 1,
	// 			toId: 1,
	// 			content: "就housekeeper1呗",
	// 			picUrlList: [
	// 				"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 				"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 				"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 				"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 				"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 				"https://tse4-mm.cn.bing.net/th/id/OIP-C.tHAIAaw4ZNlr4v2ldAkvYwHaHa?w=169&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3"
	// 			],
	// 			createdTime: "2025-07-07 15:44:59",
	// 			replyCount: 1,
	// 			likeCount: 0,
	// 			isDeleted: 0,
	// 			fromUserId: 4,
	// 			toUserId: 5,
	// 			fromUserName: "zs",
	// 			toUserName: "zhangsi",
	// 			fromUserAvatar: "https://ts1.tc.mm.bing.net/th/id/OIP-C.x1PyBhyeDOzT5_Wx5WiLJAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3",
	// 			toUserAvatar: "https://tse1-mm.cn.bing.net/th/id/OIP-C.-ha6wAB8QEtiNtN5KPygnQAAAA?w=174&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 			parentId: 1,
	// 			isLiked: false,
	// 			isAuthor: true,
	// 			nodeId: 2,
	// 			nodePId: 1
	// 		}],
	// 		id: 1,
	// 		momentId: 1,
	// 		replyType: 1,
	// 		replierAuthor: 0,
	// 		toId: null,
	// 		content: "哪个护工啊，咋的了",
	// 		picUrlList: [],
	// 		createdTime: "2025-07-07 15:42:39",
	// 		replyCount: 2,
	// 		likeCount: 1,
	// 		isDeleted: 0,
	// 		fromUserId: 5,
	// 		toUserId: null,
	// 		fromUserName: "zhangsi",
	// 		toUserName: null,
	// 		fromUserAvatar: "https://tse1-mm.cn.bing.net/th/id/OIP-C.-ha6wAB8QEtiNtN5KPygnQAAAA?w=174&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3",
	// 		toUserAvatar: null,
	// 		parentId: -1,
	// 		isLiked: false,
	// 		isAuthor: false,
	// 		nodeId: 1,
	// 		nodePId: -1
	// 	}],
	// 	isAuthor: true
	// })

	const handleLikeOrUnlike = async () => {
		console.log(momentDetail.value);
		console.log(momentDetail.value.id);
		console.log(momentDetail.value.isLiked);
		await likeOrUnlikeMoment({
			momentId: momentDetail.value.id,
			status: momentDetail.value.isLiked ? 0 : 1
		}).then(res => {
			uni.showToast({
				title: '操作成功！',
				icon: 'success'
			});
		}).catch(err => {
			uni.showToast({
				title: '操作失败！',
				icon: 'none'
			});
		});
		await getCurrentMomentDetail();
	}
	const handleDeleteMoment = () => {
		uni.showModal({
			title: '删除确认',
			content: '确定要删除这条动态吗？',
			confirmText: '删除',
			confirmColor: '#e64340',
			cancelText: '取消',
			success: async (res) => {
				if (res.confirm) {
					// 显示加载状态
					uni.showLoading({
						title: '删除中...',
						mask: true
					});

					try {
						console.log("要删除动态，id：" + momentDetail.value.id)
						await deleteMoment(momentDetail.value.id);
						uni.hideLoading();
						uni.showToast({
							title: '删除成功！',
							icon: 'success',
							duration: 2000
						});
						// 返回前一个页面
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} catch (err) {
						uni.hideLoading();
						uni.showToast({
							title: '删除失败！',
							icon: 'none',
							duration: 2000
						});
					}
				}
			}
		});
	}

	// 新评论内容
	const newCommentContent = ref('');
	// 新评论图片
	const newCommentImages = ref([]);
	// 评论提交状态
	const submittingComment = ref(false);

	// 添加评论图片
	function addCommentImage() {
		uni.chooseImage({
			count: 9 - newCommentImages.value.length,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				const tempFilePaths = res.tempFilePaths;
				// 显示上传进度
				uni.showLoading({
					title: '上传中...',
					mask: true
				});
				try {
					// 批量上传图片
					const results = await batchUploadFiles(tempFilePaths);
					// 添加新上传的图片url
					newCommentImages.value = [...newCommentImages.value, ...results];
					uni.hideLoading();
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error.message || '图片上传失败',
						icon: 'none'
					});
				}
			}
		});
	}

	// 移除评论图片
	function removeCommentImage(index) {
		newCommentImages.value.splice(index, 1);
	}

	// 提交评论
	async function submitComment() {
		if (!newCommentContent.value.trim() && newCommentImages.value.length === 0) {
			uni.showToast({
				title: '填写评论内容或添加图片',
				icon: 'none'
			});
			return;
		}
		submittingComment.value = true;
		// 提交评论
		await addCommentReply({
			momentId: momentDetail.value.id,
			replyType: 1,
			content: newCommentContent.value,
			picUrlList: newCommentImages.value,
			targetId: momentDetail.value.id,
			commentId: null
		});
		submittingComment.value = false;
		// 清空
		newCommentContent.value = '';
		newCommentImages.value = [];
		await getCurrentMomentDetail();
	}

	// 点赞/取消点赞评论
	async function toggleCommentLike(comment) {
		if (comment.isLiked) {
			console.log("取消点赞");
		} else {
			console.log("点赞");
		}
		console.log(comment.id);
		await likeOrUnlikeCommentReply({
			commentReplyId: comment.id,
			status: comment.isLiked ? 0 : 1
		}).then(res => {
			uni.showToast({
				title: '操作成功！',
				icon: 'success'
			});
		}).catch(err => {
			uni.showToast({
				title: '操作失败！',
				icon: 'none'
			});
		});
		await getCurrentMomentDetail();
	}

	// 点赞/取消点赞回复
	async function toggleReplyLike(reply) {
		await likeOrUnlikeCommentReply({
			commentReplyId: reply.id,
			status: reply.isLiked ? 0 : 1
		}).then(res => {
			uni.showToast({
				title: '操作成功！',
				icon: 'success'
			});
		}).catch(err => {
			uni.showToast({
				title: '操作失败！',
				icon: 'none'
			});
		});
		await getCurrentMomentDetail();
	}

	// 获取部分回复（最多2条）
	function getPartialReplies(comment) {
		if (!comment.children || comment.children.length === 0) {
			return [];
		}
		// 按创建时间倒序排序，确保最新回复在前
		const sortedReplies = [...comment.children].sort((a, b) =>
			new Date(b.createdTime) - new Date(a.createdTime)
		);
		// 只取前2条一级回复
		return sortedReplies.slice(0, 2);
	}

	// 展平回复树（递归函数）
	function getFlattenedReplies(comment) {
		const result = [];
		// 递归遍历函数
		function traverse(node) {
			// 添加当前节点
			result.push(node);
			// 确保子节点存在
			if (node.children && node.children.length > 0) {
				// 按创建时间倒序排序
				node.children.sort((a, b) =>
					new Date(b.createdTime) - new Date(a.createdTime)
				);
				// 遍历子节点
				node.children.forEach(child => traverse(child));
			}
		}
		// 确保评论有子回复
		if (comment.children && comment.children.length > 0) {
			// 按创建时间倒序排序一级回复
			comment.children.sort((a, b) =>
				new Date(b.createdTime) - new Date(a.createdTime)
			);
			// 遍历所有一级回复
			comment.children.forEach(child => traverse(child));
		}
		return result;
	}

	// 显示回复
	function showReplies(comment) {
		comment.showReplies = true;
	}

	// 加载所有回复
	function loadAllReplies(comment) {
		comment.showAllReplies = true;
	}

	// 回复输入框相关状态
	const showReplyInput = ref(false);
	const replyContent = ref('');
	const replyImages = ref([]);
	const sendingReply = ref(false);
	// 回复目标信息
	const replyTarget = ref(null);
	const replyTargetName = ref('');
	// 所属评论
	const replyComment = ref('');
	// 打开回复输入框
	function openReplyInput(comment, target) {
		// 设置回复目标
		replyTarget.value = target;
		// 设置回复对象名称
		replyTargetName.value = target.fromUserName;
		replyComment.value = comment;
		// 清空内容
		replyContent.value = '';
		replyImages.value = [];
		// 显示输入框
		showReplyInput.value = true;
	}
	// 关闭回复输入框
	function closeReplyInput() {
		showReplyInput.value = false;
		replyTarget.value = null;
		replyTargetName.value = '';
	}
	// 添加回复图片
	function addReplyImage() {
		uni.chooseImage({
			count: 9 - replyImages.value.length,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				const tempFilePaths = res.tempFilePaths;
				// 显示上传进度
				uni.showLoading({
					title: '上传中...',
					mask: true
				});
				try {
					// 批量上传图片
					const results = await batchUploadFiles(tempFilePaths);
					// 添加新上传的图片URL
					replyImages.value = [...replyImages.value, ...results];
					uni.hideLoading();
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error.message || '图片上传失败',
						icon: 'none'
					});
				}
			}
		});
	}
	// 移除回复图片
	function removeReplyImage(index) {
		replyImages.value.splice(index, 1);
	}
	// 发送回复
	async function sendReply() {
		if (!replyContent.value.trim() && replyImages.value.length === 0) {
			uni.showToast({
				title: '请填写内容或添加图片',
				icon: 'none'
			});
			return;
		}
		sendingReply.value = true;
		try {
			// 构建回复数据
			const replyData = {
				momentId: momentDetail.value.id,
				replyType: 2, // 回复类型为回复
				content: replyContent.value,
				picUrlList: replyImages.value,
				targetId: replyTarget.value.id, // 回复目标ID,
				commentId: replyComment.value.id
			};
			// 调用API发送回复
			await addCommentReply(replyData);
			uni.showToast({
				title: '回复成功',
				icon: 'success'
			});
			// 关闭输入框
			closeReplyInput();
			// 手动更新UI，避免收起回复列表
			// const commentIndex = momentDetail.value.commentReplyVOList.findIndex(
			// 	c => c.id === replyComment.value.id
			// );
			// if (commentIndex !== -1) {
			// 	// 确保评论是展开的
			// 	momentDetail.value.commentReplyVOList[commentIndex].showReplies = true;
			// 	// 强制刷新该评论的回复列表
			// 	momentDetail.value.commentReplyVOList[commentIndex].flattenedReplies =
			// 		getFlattenedReplies(momentDetail.value.commentReplyVOList[commentIndex]);
			// 	// 更新部分回复
			// 	momentDetail.value.commentReplyVOList[commentIndex].partialReplies =
			// 		getPartialReplies(momentDetail.value.commentReplyVOList[commentIndex]);
			// 	// 增加回复计数
			// 	momentDetail.value.commentReplyVOList[commentIndex].replyCount++;
			// 	momentDetail.value.replyCount++;
			// }
			// 可选：刷新整个动态详情
			await getCurrentMomentDetail();
		} catch (error) {
			uni.showToast({
				title: error.message || '回复失败',
				icon: 'none'
			});
		} finally {
			sendingReply.value = false;
		}
	}
	// 删除评论或回复
	async function handleDeleteCommentReply(commentReply) {
		console.log("要删除：" + commentReply);
		console.log(commentReply.id);
		uni.showModal({
			title: '删除确认',
			content: '确定要删除这条评论吗？',
			confirmText: '删除',
			confirmColor: '#e64340',
			cancelText: '取消',
			success: async (res) => {
				if (res.confirm) {
					// 显示加载状态
					uni.showLoading({
						title: '删除中...',
						mask: true
					});
					try {
						await deleteCommentReply(commentReply.id);
						uni.hideLoading();
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						// 刷新动态详情
						await getCurrentMomentDetail();
					} catch (error) {
						uni.hideLoading();
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						});
					}
				}
			}
		});
	}
	onLoad(async (options) => { // 1. 添加 async 关键字
		// 从路由选项获取传递的参数
		momentId.value = options.momentId;
		console.log('接收到的动态ID:', momentId.value);
		await getCurrentMomentDetail();
	})
</script>
<style scoped>
	.moment-detail-page {
		min-height: 100vh;
		background: url('@/static/background.png') no-repeat;
		/* background-size: cover; */
		padding-bottom: 20px;
		padding-top: 30px;
	}

	.my-navigation {
		/* margin-bottom: 80px; */
		/* border: 1px solid; */
	}

	.moment-message {
		padding: 0 16px;
		margin-top: 80px;
	}

	.title-row {
		margin-top: 5px;
		display: flex;
		align-items: flex-start;
		/* 顶部对齐 */
		flex-wrap: nowrap;
	}

	.author-info {
		flex: 1;
		/* 占据剩余空间 */
		margin-left: 10px;
		min-width: 0;
		/* 防止内容溢出 */
	}

	.author-nickname {
		font-size: 16px;
		/* 适当减小字号 */
		color: dimgrey;
		line-height: 1.2;
		/* 添加文本溢出处理 */
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.post-time {
		display: flex;
		align-items: center;
		margin-top: 2px;
		/* 与昵称保持距离 */
	}

	.created-time {
		font-size: 12px;
		color: darkgrey;
		line-height: 1.2;
	}

	.delete-btn {
		margin-left: 10px;
		/* 减少左边距 */
		width: 24px;
		height: 24px;
		flex-shrink: 0;
		/* 防止被压缩 */
	}

	.author-avatar {
		width: 40px;
		height: 40px;
		margin-left: 10px;
	}



	.delete-btn-icon {
		width: 24px;
		height: 24px;
	}

	.content {
		margin-top: 10px;
		padding-left: 8px;
		padding-right: 8px;
	}

	/* 图片网格容器 */
	.image-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		/* 三列布局 */
		gap: 8px;
		/* 图片间距 */
		padding: 10px;
	}

	/* 图片容器 */
	.image-item-container {
		position: relative;
		aspect-ratio: 1/1;
		/* 保持正方形 */
		border-radius: 4px;
		overflow: hidden;
	}

	/* 图片本身 */
	.image-item {
		width: 100%;
		height: 100%;
		object-fit: cover;
		/* 保持比例填充 */
	}

	.opreation-row {
		margin-top: 10px;
		display: flex;
		align-items: center;
		margin-left: 220px;
		margin-bottom: 20px;
	}

	.like-btn {
		width: 24px;
		height: 24px;
	}

	.like-count {
		min-width: 24px;
		margin-left: 5px;
		color: dimgrey;
		padding-bottom: 4px;
	}

	.comment-btn {
		margin-left: 10px;
		width: 24px;
		height: 24px;
	}

	.comment-count {
		margin-left: 15px;
		color: dimgrey;
		padding-bottom: 4px;
		min-width: 24px;
	}

	/* 发表评论区域 */
	.comment-input-area {
		background-color: #fff;
		border-radius: 10px;
		padding: 15px;
		margin: 20px 16px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.comment-input {
		width: 100%;
		max-height: 40px;
		/* min-height: 80px; */
		padding: 10px;
		border: 1px solid #eee;
		border-radius: 8px;
		font-size: 14px;
		margin-bottom: 10px;
	}

	.comment-image-upload {
		margin-top: 10px;
	}

	.comment-image-container {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.comment-image-preview {
		position: relative;
		width: 60px;
		height: 60px;
		border-radius: 4px;
		overflow: hidden;
	}

	.comment-image-preview image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.comment-delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 20px;
		height: 20px;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 0 0 0 8px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 14px;
	}

	.comment-add-image-btn {
		width: 60px;
		height: 60px;
		border: 1px dashed #ccc;
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f9f9f9;
	}

	.comment-add-image-btn image {
		width: 24px;
		height: 24px;
	}

	.submit-comment-btn {
		margin-top: 15px;
		background-color: #F6A031;
		color: white;
		border-radius: 20px;
		height: 40px;
		line-height: 30px;
		font-size: 14px;
	}

	.submit-comment-btn[disabled] {
		background-color: #cccccc;
	}

	/* 评论统计 */
	.comment-count-header {
		padding: 15px 16px 5px;
		font-size: 16px;
		font-weight: bold;
		color: #333;
		border-bottom: 1px solid #eee;
		margin: 0 16px;
	}

	/* 评论列表 */
	.comment-list {
		padding: 0 16px 20px;
	}

	.comment-item {
		padding: 15px 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.comment-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.comment-avatar {
		width: 36px;
		height: 36px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.comment-author {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.comment-nickname {
		font-size: 14px;
		font-weight: bold;
		color: #333;
		margin-right: 6px;
	}

	.comment-author-tag {
		font-size: 10px;
		color: #fff;
		background-color: #FF2C55;
		border-radius: 2px;
		padding: 1px 3px;
	}

	.comment-time {
		font-size: 12px;
		color: #999;
	}

	.comment-content {
		font-size: 14px;
		color: #333;
		line-height: 1.5;
		margin-bottom: 10px;
	}

	.comment-images {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
		margin-bottom: 10px;
	}

	.comment-image-item {
		width: 80px;
		height: 80px;
		border-radius: 4px;
		overflow: hidden;
	}

	.comment-image-item image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.comment-actions {
		display: flex;
		align-items: center;
	}

	.comment-like {
		display: flex;
		align-items: center;
		margin-right: 15px;
		font-size: 12px;
		color: #666;
	}

	.like-icon {
		width: 16px;
		height: 16px;
		margin-right: 4px;
	}

	.comment-reply-btn {
		font-size: 12px;
		color: #666;
	}

	/* 回复列表 */
	.reply-list {
		margin-top: 15px;
		margin-left: 15px;
		padding-left: 15px;
		border-left: 2px solid #f0f0f0;
	}

	.reply-item {
		padding: 10px 0;
		border-bottom: 1px dashed #f0f0f0;
	}

	.reply-header {
		display: flex;
		align-items: center;
		margin-bottom: 5px;
	}

	.reply-avatar {
		width: 28px;
		height: 28px;
		border-radius: 50%;
		margin-right: 8px;
	}

	.reply-author {
		font-size: 12px;
		color: #333;
	}

	.reply-nickname {
		font-weight: bold;
	}

	.reply-author-tag {
		font-size: 10px;
		color: #fff;
		background-color: #FF2C55;
		border-radius: 2px;
		padding: 1px 3px;
		margin: 0 4px;
	}

	.reply-to-nickname {
		font-weight: bold;
		/* color: #F6A031; */
	}

	.reply-content {
		font-size: 13px;
		color: #333;
		line-height: 1.5;
		margin-bottom: 5px;
	}

	.reply-images {
		display: flex;
		flex-wrap: wrap;
		gap: 6px;
		margin-bottom: 5px;
	}

	.reply-image-item {
		width: 60px;
		height: 60px;
		border-radius: 4px;
		overflow: hidden;
	}

	.reply-image-item image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.reply-actions {
		display: flex;
		align-items: center;
		font-size: 12px;
		color: #999;
	}

	.reply-time {
		margin-right: 15px;
	}

	.reply-like {
		display: flex;
		align-items: center;
		margin-right: 15px;
	}

	.reply-reply-btn {
		color: #666;
	}

	.view-more-replies {
		color: #F6A031;
		font-size: 12px;
		margin-top: 10px;
		padding: 5px 0;
	}

	/* 查看回复按钮 */
	.view-replies-btn {
		/* color: #007aff; */
		font-size: 12px;
		padding: 5px 0;
		cursor: pointer;
	}

	/* 加载全部回复按钮 */
	.load-all-replies-btn {
		/* color: #007aff; */
		font-size: 12px;
		padding: 5px 0;
		text-align: center;
		border-top: 1px dashed #eee;
		margin-top: 5px;
		cursor: pointer;
	}

	/* 回复列表 */
	.reply-list {
		margin-top: 10px;
		padding-left: 15px;
		border-left: 2px solid #f0f0f0;
	}

	/* 添加悬停效果 */
	.view-replies-btn:hover,
	.load-all-replies-btn:hover {
		text-decoration: underline;
	}

	/* 遮罩层 */
	.mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}

	/* 回复输入框容器 */
	.reply-input-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-radius: 16px 16px 0 0;
		padding: 15px;
		z-index: 1000;
		box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
	}

	/* 回复输入框头部 */
	.reply-input-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.close-btn {
		font-size: 24px;
		width: 30px;
		height: 30px;
		text-align: center;
		line-height: 30px;
		color: #999;
	}

	/* 回复文本区域 */
	.reply-textarea {
		width: 100%;
		min-height: 80px;
		padding: 10px;
		border: 1px solid #eee;
		border-radius: 8px;
		font-size: 14px;
		margin-bottom: 10px;
	}

	/* 回复图片上传区 */
	.reply-image-upload {
		margin-bottom: 10px;
	}

	.reply-image-container {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.reply-image-preview {
		position: relative;
		width: 60px;
		height: 60px;
		border-radius: 4px;
		overflow: hidden;
	}

	.reply-image-preview image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.reply-delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 20px;
		height: 20px;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 0 0 0 8px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 14px;
	}

	.reply-add-image-btn {
		width: 60px;
		height: 60px;
		border: 1px dashed #ccc;
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f9f9f9;
	}

	.reply-add-image-btn image {
		width: 24px;
		height: 24px;
	}

	/* 操作按钮 */
	.reply-action-buttons {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.reply-upload-btn {
		width: 40px;
		height: 40px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.upload-icon {
		width: 24px;
		height: 24px;
	}

	.reply-send-btn {
		background-color: #F6A031;
		color: white;
		border-radius: 20px;
		height: 36px;
		line-height: 36px;
		font-size: 14px;
		padding: 0 20px;
	}

	.reply-send-btn[disabled] {
		background-color: #cccccc;
	}

	/* 评论删除按钮 */
	.comment-item-delete-btn {
		margin-left: 15px;
		width: 20px;
		height: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 回复删除按钮 */
	.reply-item-delete-btn {
		margin-left: 15px;
		width: 16px;
		height: 16px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 删除图标 */
	.delete-icon {
		width: 100%;
		height: 100%;
	}
</style>